//-----------------------------------------------------------------------------
// Filename: ClickToCallController.cs
//
// Description: Click to Call controller for the SIP Switch.
//
// History:
// 29 Jan 2008	Aaron Clauson	Created.
//
// License: 
// Aaron Clauson.
//-----------------------------------------------------------------------------

using System;
using System.Collections;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
using MaverickLite.Security;
using BlueFace.Sys;
using log4net;

namespace SIPSwitch.Web
{
	public class ClickToCallController : SecureXmlController
	{
		private new static ILog logger = AppState.GetLogger("sipswitch");

        private static string m_switchDBConnStr = ConfigurationManager.AppSettings["SIPSwitchDBConnStr"];
        private static string m_switchStorageTypeStr = ConfigurationManager.AppSettings["SIPSwitchDBType"];
        private static string m_switchCallFlowDropDirectory = ConfigurationManager.AppSettings["CallFlowDropDirectory"];
        private static string m_switchCallFlowTemplateDirectory = ConfigurationManager.AppSettings["CallFlowTemplateDirectory"];

		private StorageLayer m_sipSwitchStorageLayer = null;

		public ClickToCallController(XmlElement initParams) : base(initParams)
		{
            m_sipSwitchStorageLayer = new StorageLayer(StorageTypesConverter.GetStorageType(m_switchStorageTypeStr), m_switchDBConnStr);
		}

		protected override void InitialiseRequest(HttpContext context)
		{
            base.InitialiseRequest(context);
		}

        public override void  BuildPageModel()
        {
			try
			{
                logger.Debug("BuildPageModel ClickToCallController.");             

                Hashtable formData = MavRequestState.GetRequestData();

                    string callSubmit = formData["Call"] as string;

                    if (callSubmit != null)
                    {
                        string server = formData["server"] as string;
                        string flowUsername = formData["flowusername"] as string;
                        string flowPassword = formData["flowpassword"] as string;
                        string firstDest = formData["firstdest"] as string;
                        string secondDest = formData["seconddest"] as string;
                        string template = formData["template"] as string;

                        string rtnFormData =
                            "<page>" +
                            " <server>" + server + "</server>" +
                            " <flowusername>" + flowUsername + "</flowusername>" +
                            " <flowpassword>" + flowPassword + "</flowpassword>" +
                            " <firstdest>" + firstDest + "</firstdest>" +
                            " <seconddest>" + secondDest + "</seconddest>" +
                            " <template>" + template + "</template>" +
                            "</page>";

                        logger.Debug("Click to call request for " + flowUsername + " and " + template + ".");

                        this.m_pageModel.AddToModel(rtnFormData, true);

                        if (server != null && server.Trim().Length > 0 &&
                            flowUsername != null && flowUsername.Trim().Length > 0 &&
                            flowPassword != null && flowPassword.Trim().Length > 0 &&
                            firstDest != null && firstDest.Trim().Length > 0 &&
                            secondDest != null && secondDest.Trim().Length > 0 && 
                            template != null && template.Trim().Length > 0)
                        {
                            if (!File.Exists(m_switchCallFlowTemplateDirectory + template))
                            {
                                logger.Warn("Click to call template does not exist " + template + ".");
                                this.m_pageModel.AddToModel("<page><error>An error has occurred, the call type was not recognised.</error></page>", true);
                            }
                            else
                            {
                                logger.Debug("Creating flow for " + flowUsername + " and " + template + ".");

                                StreamReader sr = new StreamReader(m_switchCallFlowTemplateDirectory + template);
                                string blindXferTemplate = sr.ReadToEnd();
                                sr.Close();

                                blindXferTemplate = blindXferTemplate.Replace("${server}", server);
                                blindXferTemplate = blindXferTemplate.Replace("${username}", flowUsername);
                                blindXferTemplate = blindXferTemplate.Replace("${password}", flowPassword);
                                blindXferTemplate = blindXferTemplate.Replace("${firstdest}", firstDest);
                                blindXferTemplate = blindXferTemplate.Replace("${seconddest}", secondDest);

                                StreamWriter sw = new StreamWriter(m_switchCallFlowDropDirectory + flowUsername + "-" + DateTime.Now.ToString("ddMMMyyyyHHmmss") + ".xml");
                                sw.Write(blindXferTemplate);
                                sw.Close();

                                this.m_pageModel.AddToModel("<page><result>Call successfully initiated.</result></page>", true);
                            }
                        }
                        else
                        {
                            this.m_pageModel.AddToModel("<page><error>Call not initiated, please make sure all fields are populated.</error></page>", true);
                        }
                    }
			}
			catch(Exception excp)
			{
				logger.Error("Exception SIPSwitchController. " + excp.Message);
                this.m_pageModel.AddToModel("<page><error>An exception occurred. " + SafeXML.MakeSafeXML(excp.Message) + "</error></page>", true);
			}
        }
	}
}
